// 封装有队列的Promise,限制接口访问的速度
// 主要为了减少python服务器的崩溃
import axios, { AxiosRequestConfig } from 'axios'

const _member = {
  _max: 5,
  _count: 0,
  _taskQueue: []
}

function createTask (caller, resolve, reject) {
  return () => {
    caller()
      .then(resolve)
      .catch(reject)
      .finally(() => {
        _member._count -= 1
        if (_member._taskQueue.length !== 0) {
          const task = _member._taskQueue.shift()
          // console.log('push out')
          task()
        }
      })
  }
}

function call (caller) {
  return new Promise((resolve, reject) => {
    _member._count += 1
    const task = createTask(caller, resolve, reject)
    if (_member._count >= _member._max) {
      // console.log('push in')
      _member._taskQueue.push(task)
    } else {
      task()
    }
  })
}

export function LimitAxiosPost (url, data, config, resolve, reject) {
  // debugger
  call(() => axios.post(url, data, config))
    .then(resolve)
    .catch(reject)
}
